package Classic150;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class 单词规律 {
    public boolean wordPattern(String pattern, String s) {
        /*
            使用单个哈希表思路，也可以不用set，使用mapping.containsValue()，但这样需要遍历一遍map的value
         */
        Map<Character, String> mapping = new HashMap<>();
        Set<String> set = new HashSet<>();
        char[] letters = pattern.toCharArray();
        String[] words = s.split(" ");
        if (letters.length != words.length) return false;
        for (int i = 0; i < letters.length; i++) {
            if (mapping.containsKey(letters[i])) {
                if (!mapping.get(letters[i]).equals(words[i])) return false;
            } else {
                if (set.contains(words[i])) return false;
                mapping.put(letters[i], words[i]);
                set.add(words[i]);
            }
        }
        return true;

        /*
            常规哈希表思路
         */
        /*char[] letters = pattern.toCharArray();
        String[] words = s.split(" ");
        if (words.length != letters.length) return false;
        Map<Character, String> mapping1 = new HashMap<>();
        Map<String, Character> mapping2 = new HashMap<>();
        for (int i = 0; i < letters.length; i++) {
            char letter = letters[i];
            String word = words[i];
            if (mapping1.containsKey(letter) && !mapping1.get(letter).equals(word)) return false;
            if (mapping2.containsKey(word) && !mapping2.get(word).equals(letter)) return false;
            mapping1.put(letter, word);
            mapping2.put(word, letter);
        }
        return true;*/
    }
}
